<template>
  <view class="merchant-message-container">
    <!-- 顶部标签栏 -->
    <view class="message-tabs">
      <view
        v-for="tab in tabs"
        :key="tab.type"
        class="tab-item"
        :class="{ active: activeTab === tab.type }"
        @click="activeTab = tab.type; loadMessages()"
      >
        {{ tab.name }}
      </view>
    </view>

    <!-- 消息列表 -->
    <scroll-view
      class="message-list"
      scroll-y
      @scrolltolower="loadMore"
      :lower-threshold="50"
    >
      <!-- 消息项 -->
      <view
        v-for="msg in messages"
        :key="msg.id"
        class="message-item"
        :class="{ unread: msg.readStatus === 0 }"
        @click="handleMessageClick(msg)"
      >
        <!-- 未读标记 -->
        <view v-if="msg.readStatus === 0" class="unread-badge"></view>

        <!-- 消息内容 -->
        <view class="message-content">
          <view class="message-title">{{ msg.title }}</view>
          <view class="message-text">{{ msg.content }}</view>
          <view class="message-time">{{ formatTime(msg.createTime) }}</view>
        </view>

        <!-- 右箭头 -->
        <view class="message-arrow">
          <uni-icons type="right" size="20" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="messages.length === 0 && !loading" class="empty-state">
        <view class="empty-icon">📭</view>
        <view class="empty-text">暂无消息</view>
      </view>

      <!-- 加载中 -->
      <view v-if="loading" class="loading">
        <uni-load-more :status="loadMoreStatus"></uni-load-more>
      </view>
    </scroll-view>

    <!-- 全部已读按钮 -->
    <view v-if="unreadCount > 0" class="mark-all-read">
      <button class="btn-mark-all" @click="markAllRead">全部标记已读</button>
    </view>
  </view>
</template>

<script>
import { getMerchantMessages, markMerchantMessageRead, markAllMerchantMessagesRead } from '@/api/merchant-message'
import { formatRelativeTime } from '@/utils/date'

export default {
  name: 'MerchantMessage',
  data() {
    return {
      tabs: [
        { type: null, name: '全部' },
        { type: 1, name: '订单' },
        { type: 2, name: '退款' },
        { type: 3, name: '待结算' },
        { type: 4, name: '新反馈' }
      ],
      activeTab: null,
      messages: [],
      unreadCount: 0,
      current: 1,
      size: 10,
      total: 0,
      loading: false,
      loadMoreStatus: 'more'
    }
  },
  onLoad() {
    this.loadMessages()
    this.syncUnreadFromStore()
  },
  onShow() {
    this.syncUnreadFromStore()
  },
  methods: {
    // 加载消息列表
    async loadMessages() {
      if (this.loading) return
      this.loading = true
      this.current = 1

      try {
        const res = await getMerchantMessages({
          type: this.activeTab,
          current: this.current,
          size: this.size
        })

        // 请求拦截器已返回 data（业务payload），这里直接使用
        const data = res || {}
        const total = Number(data.total) || 0
        const size = Number(data.size) || this.size
        const current = Number(data.current) || 1
        this.messages = data.records || []
        this.total = total
        this.size = size
        this.current = current
        this.loadMoreStatus = this.messages.length >= this.total ? 'noMore' : 'more'
      } catch (error) {
        uni.showToast({ title: '加载消息失败', icon: 'none' })
      } finally {
        this.loading = false
      }
    },

    // 加载更多
    async loadMore() {
      if (this.loading || this.messages.length >= this.total) return
      this.loading = true
      this.current++

      try {
        const res = await getMerchantMessages({
          type: this.activeTab,
          current: this.current,
          size: this.size
        })

        // 请求拦截器已返回 data（业务payload），这里直接使用
        const data = res || {}
        const newRecords = data.records || []
        const total = Number(data.total) || this.total
        this.total = total
        this.messages = [...this.messages, ...newRecords]
        this.loadMoreStatus = this.messages.length >= this.total ? 'noMore' : 'more'
      } catch (error) {
        uni.showToast({ title: '加载失败', icon: 'none' })
      } finally {
        this.loading = false
      }
    },

    // 从 store 同步未读数（不再发请求）
    syncUnreadFromStore() {
      this.unreadCount = Number(this.$store.state.merchantUnreadCount) || 0
    },

    // 消息点击处理
    async handleMessageClick(msg) {
      // 标记已读
      if (msg.readStatus === 0) {
        try {
          await markMerchantMessageRead(msg.id)
          msg.readStatus = 1
          // 同步更新全局未读数
          this.$store.commit('DECREMENT_MERCHANT_UNREAD_COUNT', 1)
          this.unreadCount = Math.max(0, this.unreadCount - 1)
        } catch (error) {
          console.error('标记已读失败', error)
        }
      }

      // 根据业务类型跳转
      if (msg.bizType === 'order' && msg.bizId) {
        // 订单：跳到商家订单列表，并携带focusId以便定位（如页面支持）
        uni.navigateTo({ url: `/pages/merchant/orders?focusId=${msg.bizId}` })
      } else if (msg.bizType === 'settlement' && msg.bizId) {
        // 结算：跳到结算管理页面，并携带orderId
        uni.navigateTo({ url: `/pages/merchant/settlement?orderId=${msg.bizId}` })
      } else if (msg.bizType === 'feedback' && msg.bizId) {
        // 反馈：直接传递消息数据给详情页（消息本身包含反馈的基本信息）
        // 避免调用 getFeedbackDetail 导致的权限问题
        uni.navigateTo({
          url: `/pages/merchant/feedback-detail?id=${msg.bizId}`,
          success: (res) => {
            // 通过 eventChannel 传递消息数据作为反馈基本信息
            // 详情页只需加载回复列表，无需再次请求反馈详情
            res.eventChannel && res.eventChannel.emit && res.eventChannel.emit('feedbackData', {
              id: msg.bizId,
              title: msg.title,
              content: msg.content,
              createTime: msg.createTime
            })
          }
        })
      } else {
        uni.showToast({ title: '暂无详情', icon: 'none' })
      }
    },

    // 全部标记已读
    async markAllRead() {
      try {
        await markAllMerchantMessagesRead()
        this.messages.forEach(msg => {
          msg.readStatus = 1
        })
        this.unreadCount = 0
        // 清空全局商家未读数
        this.$store.commit('SET_MERCHANT_UNREAD_COUNT', 0)
        uni.showToast({ title: '已全部标记为已读', icon: 'success' })
      } catch (error) {
        uni.showToast({ title: '操作失败', icon: 'none' })
      }
    },

    // 格式化时间
    formatTime(time) {
      return formatRelativeTime(time)
    }
  }
}
</script>

<style scoped lang="scss">
.merchant-message-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.message-tabs {
  display: flex;
  background-color: white;
  border-bottom: 1px solid #eee;
  overflow-x: auto;

  .tab-item {
    flex: 0 0 auto;
    padding: 12px 16px;
    color: #666;
    font-size: 14px;
    white-space: nowrap;
    border-bottom: 3px solid transparent;
    transition: all 0.3s;

    &.active {
      color: #007aff;
      border-bottom-color: #007aff;
    }
  }
}

.message-list {
  flex: 1;
  overflow-y: auto;
}

.message-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  margin: 8px 0;
  background-color: white;
  border-radius: 8px;
  margin-left: 8px;
  margin-right: 8px;
  position: relative;

  &.unread {
    background-color: #f0f7ff;
  }

  .unread-badge {
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 4px;
    background-color: #ff3b30;
    border-radius: 50%;
  }
}

.message-content {
  flex: 1;
  margin-left: 12px;
  min-width: 0;

  .message-title {
    font-size: 15px;
    font-weight: 500;
    color: #333;
    margin-bottom: 4px;
  }

  .message-text {
    font-size: 13px;
    color: #666;
    margin-bottom: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .message-time {
    font-size: 12px;
    color: #999;
  }
}

.message-arrow {
  margin-left: 8px;
  color: #ccc;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #999;

  .empty-icon {
    font-size: 48px;
    margin-bottom: 12px;
  }

  .empty-text {
    font-size: 14px;
  }
}

.loading {
  padding: 20px;
}

.mark-all-read {
  padding: 12px 16px;
  background-color: white;
  border-top: 1px solid #eee;

  .btn-mark-all {
    width: 100%;
    padding: 12px;
    background-color: #007aff;
    color: white;
    border-radius: 8px;
    font-size: 14px;
    border: none;
  }
}
</style>
